package com.java.comprehensive.other.config.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;
import util.IpUtil;

/**
 * 描述:通过@Aspect注解使该类成为切面类 
 */
@Aspect
@Component
@Slf4j
public class LoginAnnoImpl {

	@Pointcut("@within(com.java.comprehensive.other.config.annotation.LogAnnontation)")
	private void cut() {
	}

	/**
	 *  功能:前置通知 
	 */
	@Before("cut()")
	public void before(JoinPoint joinPoint) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes != null) {
			HttpServletRequest servletRequest = attributes.getRequest();
			// 打印请求相关参数
			log.info("========================================== Start ==========================================");
			// 打印请求 url
			log.info("URL            : {}", servletRequest.getRequestURL().toString());
			// 打印 Http method
			log.info("HTTP Method    : {}", servletRequest.getMethod());
			// 打印调用 controller 的全路径以及执行方法
			log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
			// 打印请求的 IP
			log.info("IP             : {}", IpUtil.getIpFromRequest(servletRequest));
			// 打印请求入参
			log.info("Request Args   : {}", new Gson().toJson(joinPoint.getArgs()));
		}
	}

	/**
	 * 环绕
	 * @param proceedingJoinPoint
	 * @return
	 * @throws Throwable
	 */
	@Around("cut()")
	public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		long startTime = System.currentTimeMillis();
		Object result = proceedingJoinPoint.proceed();
		// 打印出参
		log.info("Response Args  : {}", new Gson().toJson(result));
		// 执行耗时
		log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
		return result;
	}
}